import { PrismaClient } from "@prisma/client"
import jwt from "jsonwebtoken"
import "dotenv/config"

const p = new PrismaClient()

export default async (req,res,next)=>{
    try{
        const [key, token]=req.headers["authorization"].split(" ")
        if(key==="Bearer" && token){
            const info = jwt.verify(token,process.env.SECRET)
            const user = await p.user.findUnique({
                where: {
                    id: info.id,
                    token
                }
            })
            if(user){
                //console.log(user);
                req.user = user
                next()
            }
            else{
                res.status(401).json({
                    msg: "Unauthorized"
                })
            }
        }
        else{
            res.status(401).json({
                msg: "Unauthorized"
            })
        }
    }
    catch(e){
        //console.log(e);
        
        res.status(401).json({
            msg: "Unauthorized"
        })
    }
    
}